package com.nuanshui.heatedloan.msgcenter.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.nuanshui.framework.lang.SysStringUtils;
import com.nuanshui.heatedloan.constant.GlobalParam;
import com.nuanshui.heatedloan.dubbo.extension.DubboContextManager;
import com.nuanshui.heatedloan.middleware.msgcenter.util.MsgParamsUtil;
import com.nuanshui.heatedloan.msgcenter.facade.MsgSender;
import com.nuanshui.heatedloan.middleware.msgcenter.bean.MsgBody;
import com.nuanshui.heatedloan.msgcenter.model.MsgType;
import com.nuanshui.heatedloan.msgcenter.processor.SmsMsgProcessor;
import com.nuanshui.heatedloan.msgcenter.processor.AppPushMsgProcessor;
import com.nuanshui.heatedloan.userinfo.facade.UserQueryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * 消息发送实现类
 *
 * @author guohao
 * @ClassName: MsgSendImpl
 * @date 2016年2月17日 上午10:54:44
 */
@Service
public class MsgSendImpl implements MsgSender ,InitializingBean{

    private Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    private SmsMsgProcessor smsMsgProcessor;

    @Autowired
    private AppPushMsgProcessor appPushMsgProcessor;

    @Reference(url = GlobalParam.USER_DUBBO_SERVER, timeout = GlobalParam.DUBBO_SERVER_TIME_OUT,version = GlobalParam.USER_DUBBO_SERVER_VERSION)
    private UserQueryService userQueryService;

    @Override
    public void sendPushMsg(MsgBody msgBody) {
        //处理推送的参数

        if(SysStringUtils.isNotEmpty(msgBody.getBizType()))
        {
            MsgParamsUtil.handlerMsgParams(msgBody.getBizType(), msgBody);
        }

        try {
            if (msgBody.getMsgType() == MsgType.SMS_MSG) {//如果是短信
                List<String> phones = msgBody.getPhones();
                if (CollectionUtils.isEmpty(phones)) {
                    phones = userQueryService.loadPhoneListByIds(msgBody.getDstUserIds());
                    msgBody.addPhones(phones);
                }
                smsMsgProcessor.execute(msgBody);
            } else if (msgBody.getMsgType() == MsgType.PUSH_MSG) {//如果是推送消息
                appPushMsgProcessor.execute(msgBody);
            }
        } catch (Exception e) {
            log.error("消息发送失败....", e);
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        userQueryService= DubboContextManager.getDubboBean(UserQueryService.class,GlobalParam.USER_DUBBO_SERVER_VERSION);
    }
}
